package com.nari.ncps.screen.service.impl.electric;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nari.ncps.screen.mapper.electric.ElectricProdoperCoalConsumeUrMapper;
import com.nari.ncps.screen.service.electric.ElectricProdoperCoalConsumeUrService;
import com.nari.ncps.screen.vo.electric.PowerRateDataItemVO;
import com.nari.ncps.screen.vo.electric.PowerRateOverviewVO;
import com.nari.ncps.screen.entity.electric.ElectricProdoperCoalConsumeUr;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.util.*;

/**
 * <p>
 * 综合厂用电率表 服务实现类
 * </p>
 *
 * @author xuesong
 * @since 2025-08-23
 */
@Service
public class ElectricProdoperCoalConsumeUrServiceImpl extends ServiceImpl<ElectricProdoperCoalConsumeUrMapper, ElectricProdoperCoalConsumeUr> implements ElectricProdoperCoalConsumeUrService {

    /**
     * 综合厂用电率概览
     * @param year 年份（可选，默认当前年）
     * @return PowerRateOverviewVO包含：yearAverage(全年平均用电率)、yoyChange(同比增加)、dataList(详细数据列表)
     */
    @Override
    public PowerRateOverviewVO getPowerRateOverview(Integer year) {
        // 如果用户没有传入year参数，默认查询当前年份
        if (year == null) {
            year = LocalDate.now().getYear();
        }
        
        // 创建返回对象
        PowerRateOverviewVO overview = new PowerRateOverviewVO();
        
        // 查询指定年份的数据
        List<ElectricProdoperCoalConsumeUr> currentYearData = this.lambdaQuery()
                .eq(ElectricProdoperCoalConsumeUr::getYear, year)
                .orderByAsc(ElectricProdoperCoalConsumeUr::getMonth)
                .list();
        
        // 如果数据为空，返回空对象
        if (currentYearData == null || currentYearData.isEmpty()) {
            overview.setYearAverage(BigDecimal.ZERO);
            overview.setYoyChange(BigDecimal.ZERO);
            overview.setDataList(new ArrayList<>());
            return overview;
        }
        
        // 按月份和电厂分组，将相同月份相同电厂的用电率求和
        Map<String, PowerRateDataItemVO> groupedData = new HashMap<>();
        
        for (ElectricProdoperCoalConsumeUr item : currentYearData) {
            if (item.getElectricityRate() == null) {
                continue;
            }
            
            // 使用月份+电厂编码作为key
            String key = item.getMonth() + "_" + 
                        (item.getOrgCode() != null ? item.getOrgCode() : "unknown");
            
            if (groupedData.containsKey(key)) {
                // 如果已存在，累加用电率
                PowerRateDataItemVO existing = groupedData.get(key);
                BigDecimal newRate = existing.getElectricityRate().add(item.getElectricityRate());
                existing.setElectricityRate(newRate);
            } else {
                // 如果不存在，创建新的数据项
                PowerRateDataItemVO dataItem = new PowerRateDataItemVO();
                dataItem.setYear(item.getYear());
                dataItem.setMonth(item.getMonth());
                dataItem.setPowerPlantCode(item.getOrgCode());
                dataItem.setPowerPlantName(item.getOrgName());
                dataItem.setElectricityRate(item.getElectricityRate());
                groupedData.put(key, dataItem);
            }
        }
        
        // 将分组后的数据转换为列表，并按月份排序
        List<PowerRateDataItemVO> dataList = new ArrayList<>(groupedData.values());
        dataList.sort(Comparator.comparing(PowerRateDataItemVO::getMonth)
                .thenComparing(item -> item.getPowerPlantCode() != null ? item.getPowerPlantCode() : ""));
        
        overview.setDataList(dataList);
        
        // 计算全年平均用电率（基于分组后的数据）
        BigDecimal yearAverage = BigDecimal.ZERO;
        if (!dataList.isEmpty()) {
            BigDecimal sum = dataList.stream()
                    .map(PowerRateDataItemVO::getElectricityRate)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            
            yearAverage = sum.divide(BigDecimal.valueOf(dataList.size()), 4, RoundingMode.HALF_UP);
        }
        overview.setYearAverage(yearAverage);
        
        // 查询上一年的数据，用于计算同比增加
        List<ElectricProdoperCoalConsumeUr> lastYearData = this.lambdaQuery()
                .eq(ElectricProdoperCoalConsumeUr::getYear, year - 1)
                .list();
        
        // 计算同比增加
        BigDecimal yoyChange = BigDecimal.ZERO;
        if (lastYearData != null && !lastYearData.isEmpty()) {
            // 按月份和电厂分组去年数据
            Map<String, BigDecimal> lastYearGrouped = new HashMap<>();
            for (ElectricProdoperCoalConsumeUr item : lastYearData) {
                if (item.getElectricityRate() == null) {
                    continue;
                }
                String key = item.getMonth() + "_" + 
                            (item.getOrgCode() != null ? item.getOrgCode() : "unknown");
                
                lastYearGrouped.merge(key, item.getElectricityRate(), BigDecimal::add);
            }
            
            // 计算去年平均用电率
            if (!lastYearGrouped.isEmpty()) {
                BigDecimal lastYearSum = lastYearGrouped.values().stream()
                        .reduce(BigDecimal.ZERO, BigDecimal::add);
                
                BigDecimal lastYearAverage = lastYearSum.divide(
                        BigDecimal.valueOf(lastYearGrouped.size()), 4, RoundingMode.HALF_UP);
                
                if (lastYearAverage.compareTo(BigDecimal.ZERO) > 0) {
                    // 同比增长率 = (今年平均 - 去年平均) / 去年平均 * 100
                    yoyChange = yearAverage.subtract(lastYearAverage)
                            .divide(lastYearAverage, 4, RoundingMode.HALF_UP)
                            .multiply(BigDecimal.valueOf(100));
                }
            }
        }
        overview.setYoyChange(yoyChange);
        
        return overview;
    }

}